import type { AxiosRequestConfig } from "axios";
// 是否给接口url添加前缀，单体应用时为false，微服务应用，通过网关访问时，为true
const usePrefix: boolean = JSON.parse(import.meta.env.VITE_API_USE_GATEWAY || 'false')

/**
 * @param {string} url
 * @returns {Boolean}
 */
export function isExternalLink(url: string): boolean {
  return /^(https?:|mailto:|tel:)/.test(url)
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type ApiConfigFun = (...args: any) => AxiosRequestConfig

export function defineApis<S extends Record<string, AxiosRequestConfig | ApiConfigFun>>(prefix: string, apis: S): S {
  if (usePrefix) {
    return Object.keys(apis).reduce((_apis, prop) => {
      const api = apis[prop]
      if (typeof api == "object") {
        const _api = { ...api };
        if (_api.url && !isExternalLink(_api.url)) {
          _api.url = prefix + _api.url;
          if (_api.url.charAt(0) != '/') {
            _api.url = '/' + _api.url
          }
          Object.defineProperty(_apis, prop, { value: _api })
        }
      } else {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const _api = function (...args: any) {
          const _api = api(...args)
          _api.url = prefix + _api.url;
          if (_api.url.charAt(0) != '/') {
            _api.url = '/' + _api.url
          }
          return _api;
        };
        Object.defineProperty(_apis, prop, { value: _api })
      }
      return _apis
    }, apis)
  } else {
    return apis
  }

}